package com.zheng.oss.rpc.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zheng.common.annotation.BaseService;
import com.zheng.common.base.BaseServiceImpl;
import com.zheng.oss.common.constant.enums.FilePermission;
import com.zheng.oss.dao.mapper.OssFileMapper;
import com.zheng.oss.dao.model.OssFile;
import com.zheng.oss.dao.model.OssRoleFile;
import com.zheng.oss.dao.model.OssShareFile;
import com.zheng.oss.dto.FolderDto;
import com.zheng.oss.dto.ShareFileDto;
import com.zheng.oss.rpc.api.OssFileService;
import com.zheng.oss.rpc.api.OssRoleFileService;
import com.zheng.oss.rpc.api.OssShareFileService;
import com.zheng.upms.dao.model.UpmsRole;
import com.zheng.upms.dao.model.UpmsUser;
import com.zheng.upms.rpc.api.UpmsApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author likun
 * @since 2018-05-08
 */
@Service
@Transactional(rollbackFor = Exception.class)
@BaseService
public class OssFileServiceImpl extends BaseServiceImpl<OssFileMapper, OssFile> implements OssFileService {
    @Autowired
    private OssFileMapper fileMapper;
    @Autowired
    private OssRoleFileService roleFileService;
    @Autowired
    private OssShareFileService shareFileService;
    @Autowired
    private UpmsApiService apiService;

    @Override
    public OssFile insertFile(OssFile file) {
        insert(file);
        return file;
    }

    public List<Map<String, Object>> selectFilePage(OssFile file) {
        return fileMapper.selectFilePage(file);
    }

    public Integer selectFilePageCount(OssFile file) {
        return fileMapper.selectFilePageCount(file);
    }

    @Override
    public boolean deleteFile(String ids, String username, Boolean isSystem) throws Exception {
        boolean result = false;
        EntityWrapper<OssFile> fileEntityWrapper;
        String[] idStrArray = ids.split("-");
        if (isSystem) {
            UpmsUser user = apiService.selectUpmsUserByUsername(username);
            List<UpmsRole> roles = apiService.selectUpmsRoleByUpmsUserIdByCache(user.getUserId());
            List<Integer> roleIds = new ArrayList<>();
            for (UpmsRole role : roles) {
                roleIds.add(role.getRoleId());
            }
            EntityWrapper<OssRoleFile> roleFileEntityWrapper;
            for (String idStr : idStrArray) {
                Integer id = Integer.parseInt(idStr);
                roleFileEntityWrapper = new EntityWrapper<>();
                roleFileEntityWrapper.eq("file_id", id).eq("permission", FilePermission.ALL.getKey()).in("role_id", roleIds);
                if (roleFileService.selectCount(roleFileEntityWrapper) < 1) {
                    throw new Exception("当前用户未拥有权限！");
                }
            }
        }
        //遍历id 然后找到该文件或该文件夹内的所有内容并删除
        for (String idStr : idStrArray) {
            Integer id = Integer.parseInt(idStr);
            fileEntityWrapper = new EntityWrapper<>();
            fileEntityWrapper.where("id=" + id).or("path like '%," + id + ",%'");
            List<OssFile> ossFiles = selectList(fileEntityWrapper);
            if (ossFiles != null && ossFiles.size() > 0) {
                for (OssFile file : ossFiles) {
                    file.setStatus(OssFile.DELETE_STATUS);
                }
                result = updateBatchById(ossFiles);
            }
        }
        return result;
    }

    public boolean createFolder(FolderDto folder, String username) throws Exception {
        UpmsUser upmsUser = apiService.selectUpmsUserByUsername(username);
        Integer pid = folder.getPid();
        String filename = folder.getFolderName();
        boolean isSystem = folder.getSystem();
        //判断权限
        if(isSystem){
            List<UpmsRole> roles = apiService.selectUpmsRoleByUpmsUserIdByCache(upmsUser.getUserId());
            List<Integer> roleIds = new ArrayList<>();
            for (UpmsRole role : roles) {
                roleIds.add(role.getRoleId());
            }
            EntityWrapper<OssRoleFile> roleFileEntityWrapper = new EntityWrapper<>();
            roleFileEntityWrapper.eq("file_id", pid).eq("permission", FilePermission.ALL.getKey()).in("role_id", roleIds);
            if (roleFileService.selectCount(roleFileEntityWrapper) < 1) {
                throw new Exception("当前用户未拥有权限！");
            }
        }
        //判断同名
        EntityWrapper<OssFile> fileEntityWrapper = new EntityWrapper<>();
        fileEntityWrapper.eq("pid", pid)
                .eq("filename", filename)
                .eq("cuser", upmsUser.getUserId())
                .eq("status", OssFile.NORMAL_STATUS);
        if (selectCount(fileEntityWrapper) > 0) {
            throw new Exception("当前目录下已有同名文件！");
        }
        OssFile pFile = selectById(pid);
        OssFile file = new OssFile();
        file.setPid(pid);
        file.setCuser(upmsUser.getUserId());
        file.setCorganization(upmsUser.getOrganizationId());
        file.setFilename(filename);
        file.setFileType(OssFile.FOLDER_TYPE);
        file.setCtime(new Date());
        file.setStatus(OssFile.NORMAL_STATUS);
        file.setPath(pFile.getPath() + pid + ",");
        insert(file);
        return roleFileService.insertRoleFile(file);
    }

    public boolean insertShare(List<Integer> userIdList, List<Integer> fileIdList) {
        OssShareFile shareFile;
        boolean result = false;
        for (Integer userId : userIdList) {
            for (Integer fileId : fileIdList) {
                shareFile = new OssShareFile();
                shareFile.setFileId(fileId);
                shareFile.setUserId(userId);
                result = shareFileService.insert(shareFile);
            }
        }
        return result;
    }

    public List<Map<String, Object>> selectShareFilePage(ShareFileDto shareFileDto) {
        return fileMapper.selectShareFilePage(shareFileDto);
    }

    public Integer selectShareFilePageCount(ShareFileDto shareFileDto) {
        return fileMapper.selectShareFilePageCount(shareFileDto);
    }

    public boolean updateSystemFile(OssFile file, String username) throws Exception {
        UpmsUser user = apiService.selectUpmsUserByUsername(username);
        List<UpmsRole> roles = apiService.selectUpmsRoleByUpmsUserIdByCache(user.getUserId());
        List<Integer> roleIds = new ArrayList<>();
        roles.forEach(role -> roleIds.add(role.getRoleId()));
        EntityWrapper<OssRoleFile> roleFileEntityWrapper = new EntityWrapper<>();
        roleFileEntityWrapper.eq("file_id", file.getId()).and("permission >=" + FilePermission.UPDATE.getKey())
                .in("role_id", roleIds);
        if (roleFileService.selectCount(roleFileEntityWrapper) < 1) {
            throw new Exception("当前用户没有修改该文件的权限！");
        }
        OssFile oldFile = selectById(file);
        EntityWrapper<OssFile> fileEntityWrapper = new EntityWrapper<>();
        fileEntityWrapper.eq("cuser", oldFile.getCuser()).eq("filename", file.getFilename()).eq("pid", oldFile.getPid());
        if (selectCount(fileEntityWrapper) > 1) {
            throw new Exception("当前目录下有相同名称的文件！");
        }
        return updateById(file);

    }

    public List<OssFile> selectFileTree(OssFile file) {
        return fileMapper.selectFileTree(file);
    }

}
